package com.zeeephr.core;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;

public class Dispartcher implements Runnable{
	
	Socket client=null;
	Request req=null;
	Response resp=null;
	Servlet myServlet=null;
	String url="";
	
	
	public Dispartcher(Socket client) {
		this.client=client;
	}
	@Override
	public void run() {
		init();//初始化一个新的req 和resp
		disp();//根据url的不同返回不同数据
	}
	public void init() {
		try {
			req = new Request(client.getInputStream());//初始化的时候就处理完发送过来的请求
			resp=new Response(client.getOutputStream());
			url=req.getUrl();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("response 和request 初始化失败");
		}
	}
	public void disp() {
		if("".equals(url)) {//如果没有url  就访问默认index.html页面
			try {
				resp.readHtml("index.html");
				resp.send(200);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		else {
			try {
				myServlet=Server.tool.getServletByURL(url);	
				if(myServlet==null) {//如果在web.xml中找不到对应servlet，则返回404
					resp.readHtml("Error.html");
					resp.send(404);
				}else {
					myServlet.service(req,resp);//找到了servlet，使用servlet进行处理
					resp.send(200);
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				try {
					resp.readHtml("500.html");//异常 则返回500页面
					resp.send(500);
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				e.printStackTrace();
			}
		}
	}
}
